package com.hy.ruiji.filter;

import com.alibaba.fastjson.JSON;
import com.hy.ruiji.common.R;
import com.hy.ruiji.common.Status;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否已经完成登录
 */
@WebFilter(filterName = "LoginCheckinFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckinFilter implements Filter {
    //路径匹配器，支持通配符匹配
    public static  final AntPathMatcher PATH_MATCHER=new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        //1、获取本次请求的url
        String requestURI = request.getRequestURI();
        log.info("拦截到请求：{}",requestURI);
        String[] urls=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
        //2、判断这次请求是否需要处理
        boolean check = check(urls, requestURI);
        if(check){
            log.info("本次请求{}不需要处理",requestURI);
            filterChain.doFilter(request,response);
            return;
        }
        //3-1、获取session，查看是否登录
        if(request.getSession().getAttribute(Status.SESSION_USER)!=null){
            log.info("用户已经登录，本次请求{}不处理",requestURI);
            //获取session里面的id，并且放到ThreadLocal
            Long empId = (Long)request.getSession().getAttribute(Status.SESSION_USER);
            Status.setCurrentId(empId);

            filterChain.doFilter(request,response);
            return;
        }
        //3-2、获取session，查看是否登录
        if(request.getSession().getAttribute("user")!=null) {
            log.info("用户已经登录，本次请求{}不处理", requestURI);
            //获取session里面的id，并且放到ThreadLocal
            Long userId = (Long) request.getSession().getAttribute("user");
            Status.setCurrentId(userId);

            filterChain.doFilter(request, response);
            return;
        }
        //未登录则返回未登录信息，通过输出流方式向客户端反应数据，json数据
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    /**
     * 路径匹配，本次请求是否需要放行
     * @param urls 需要放行的请求
     * @param requestURI 本次请求的url
     * @return 返回结果
     */
    public boolean check(String[] urls,String requestURI){
        for(String url:urls){
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }
}

